package com.yiman.project.system.web;

import com.alibaba.fastjson.JSON;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author: ym
 * @create: 2019-05-01
 **/

@Controller
public class LoginController {

    private static final Logger log = LoggerFactory.getLogger(LoginController.class);

    @RequestMapping({"/login", "/"})
    public String login() {
        return "login";
    }

    @PostMapping("/login")
    @ResponseBody
    public String ajaxlogin(String username, String password) {
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            Object obj = subject.getPrincipal();
            log.info("从subject中获取的user:" + JSON.toJSONString(obj));
            Session session = subject.getSession();
            session.setAttribute("userSession", obj);
            return "0";
        } catch (AuthenticationException e) {
            return "1";
        }
    }


    @RequestMapping("/welcome")
    //@ResponseBody
    public String welcome(ModelMap map) {
        map.put("rrr", "hello");
        return "welcome";
    }


}
